<script setup>
import { ref, reactive, onMounted, nextTick, onUnmounted } from 'vue'
import { Delete, CirclePlus, Share, RefreshLeft, RefreshRight, ZoomIn, ZoomOut } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Pavo from './pavo/index.js'

const size = reactive({
    width: 640,
    height: 480
})

const editor = ref(null)
let scene = null
let uid = 0

const onContainerResize = () => {
    size.width = editor.value.clientWidth
    size.height = editor.value.clientHeight
    nextTick(() => {
        scene.resize(size.width, size.height)
    })
}

// 使用防抖 (setTimeout定时器)
const debounce = (fn, delay) => {
    let timer;
    return function () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn()
        }, delay)
    }
}
const cancalDebounce = debounce(onContainerResize, 500)


onMounted(() => {
    scene = Pavo.init({
        container: 'scene',  //container 用来容纳舞台的容器
        width: size.width,
        height: size.height,
        showMouseInfo: false
    })

    onContainerResize()
    // 监听Resize事件
    window.addEventListener('resize', cancalDebounce)
})

onUnmounted(() => {
    //移除监听事件
    window.removeEventListener('resize', cancalDebounce);
})

const clear = () => {
}

const zoomIn = () => {
    scene.zoomIn()
}

const zoomOut = () => {
    scene.zoomOut()
}

const reset = () => {
    scene.reset()
}

const undo = () => {
    scene.undo()
}

const redo = () => {
    scene.redo()
}

const add = () => {
    let data = {
        title: '实体' + uid++,
        fill: '#FFFFFF'
    }
    scene.addNode('entity', data)
    scene.snapshot()
}

</script>

<template>
    <div class="container" ref="editor">
        <div id="scene"></div>
        <div class="nav">
            <el-button-group>
                <el-button type="primary" :icon="ZoomIn" @click="zoomIn"></el-button>
                <el-button type="primary" :icon="ZoomOut" @click="zoomOut"></el-button>
                <el-button type="primary" :icon="Share" @click="reset"></el-button>
                <el-button type="primary" :icon="RefreshLeft" @click="undo"></el-button>
                <el-button type="primary" :icon="RefreshRight" @click="redo"></el-button>
                <el-button type="primary" :icon="Delete" @click="clear"></el-button>
                <el-button type="primary" :icon="CirclePlus" @click="add"></el-button>
            </el-button-group>
        </div>
    </div>
</template>

<style scoped>
.container {
    height: 100%;
    display: flex;
    position: relative;
    background-color: #E5E6EB;
}

#scene {
    flex: 1;
}

.nav {
    position: absolute;
    top: 0;
    right: 0;
}
</style>
